package com.machine.filling.function.main.activity.adapter;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.machine.filling.R;
import com.machine.filling.db.modle.AdModle;
import com.machine.filling.util.FileUtils;
import com.machine.filling.util.LogUtil;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/3/12 0012.
 * 广告适配器
 */

public class ADPagerAdapter extends PagerAdapter {
    private static final String TAG = "AdPagerAdapter";
    private Context mContext;
    private List<AdModle> listBean;
    private MediaPlayer mPlayer;
    private SurfaceView surfaceview;
    private final String fileDir;

    public ADPagerAdapter(Context mContext, List<AdModle> listBean) {
        this.mContext = mContext;
        if (listBean == null || listBean.size() == 0) {
            this.listBean = new ArrayList<>();
        } else {
            this.listBean = listBean;
        }
        initMediaPlayer();

        fileDir = Environment.getExternalStorageDirectory()
                .getAbsolutePath()
                + File.separator
                + "XDKJ/ad";
    }

    private void initMediaPlayer() {
        if (mPlayer != null){
            mPlayer.reset();
        }
        mPlayer = getMediaPlayer(mContext);
        mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mPlayer.start();
            }
        });
        mPlayer.setOnErrorListener(onErrorListener);
    }

    private void destoryMediaPlayer() {
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                mPlayer.stop();
            }
            mPlayer.release();
            mPlayer = null;
        }
    }

    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_ad, null);
        ImageView imageView = view.findViewById(R.id.iv_ad);
        final ProgressBar progress = view.findViewById(R.id.progress);
        SurfaceView surfaceview = view.findViewById(R.id.surfaceview);

        String fileName = listBean.get(position).getHttpImgPath()
                .substring(
                        listBean.get(position).getHttpImgPath().lastIndexOf("/")+1);

        boolean isLocalExist = FileUtils.isFileExist(fileName,fileDir,false);

        String mediaPath = isLocalExist
                ? fileDir + File.separator +  fileName: listBean.get(position).getLocalImgPath();

        Log.d(TAG, "本地地址是: " + listBean.get(position).getLocalImgPath());
        Log.d(TAG, "加载的地址是: " + mediaPath);
        if (listBean.get(position).getType() == 1 ) {//图片
            imageView.setVisibility(View.VISIBLE);
            surfaceview.setVisibility(View.GONE);
            progress.setVisibility(View.GONE);

            destoryMediaPlayer();
            Glide.with(mContext).load(mediaPath)
                    .centerCrop()
                    .into(imageView);
        } else {//视频
            imageView.setVisibility(View.GONE);
            surfaceview.setVisibility(View.VISIBLE);
            progress.setVisibility(View.VISIBLE);
            initMediaPlayer();
            try {

                mPlayer.setDataSource(mediaPath);
                mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        progress.setVisibility(View.GONE);
                        mPlayer.start();
                        mPlayer.setLooping(true);
                    }
                });
                //把视频画面输出到SurfaceView
                mPlayer.prepareAsync();
            } catch (Exception e) {
                e.printStackTrace();
            }
            surfaceview.getHolder().addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                    mPlayer.setDisplay(holder);
                }

                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                }

                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    Log.d(TAG, "surfaceDestroyed() returned: " );
                }
            });

        }
        container.addView(view);
        return view;
//            final MyVideoView videoView = new MyVideoView(mContext);
//            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
//                @Override
//                public void onPrepared(MediaPlayer mediaPlayer) {
//                    mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
//
//                        @Override
//                        public boolean onInfo(MediaPlayer mp, int what, int extra) {
//                            if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
//                                videoView.setBackgroundColor(Color.TRANSPARENT);
//                            return true;
//                        }
//                    });
//                }
//            });
//            videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//                @Override
//                public void onCompletion(MediaPlayer mp) {
//                    Log.d("", "onCompletion() returned: " + "视频结束");
//                }
//            });
//
//            videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
//                @Override
//                public boolean onError(MediaPlayer mp, int what, int extra) {
//                    return true;
//                }
//            });
//
//            try {
//                videoView.setVideoURI(Uri.parse(listBean.get(position).getImgPath()/*Environment.getExternalStorageDirectory()
//                        .getAbsolutePath()
//                        + File.separator
//                        + File.separator
//                        + "XDKJ" + File.separator + "ad" + File.separator + "1.mp4"*/));
//            } catch (Exception e) {
//                Log.d("", "instantiateItem() returned: " + e.toString());
//            }
//            //开始播放
//            videoView.start();
//            container.addView(videoView);
//            return videoView;
//        }


    }

    //PagerAdapter只缓存三张要显示的图片，如果滑动的图片超出了缓存的范围，就会调用这个方法，将图片销毁
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    //获取要滑动的控件的数量，
    @Override
    public int getCount() {
        return listBean.size();
    }

    //来判断显示的是否是同一张照片，这个我们将两个图片对比 再返回
    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    private MediaPlayer getMediaPlayer(Context context) {
        MediaPlayer mediaplayer = new MediaPlayer();
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
            return mediaplayer;
        }
        try {
            Class<?> cMediaTimeProvider = Class.forName("android.media.MediaTimeProvider");
            Class<?> cSubtitleController = Class.forName("android.media.SubtitleController");
            Class<?> iSubtitleControllerAnchor = Class.forName("android.media.SubtitleController$Anchor");
            Class<?> iSubtitleControllerListener = Class.forName("android.media.SubtitleController$Listener");
            Constructor constructor = cSubtitleController.getConstructor(
                    new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});
            Object subtitleInstance = constructor.newInstance(context, null, null);
            Field f = cSubtitleController.getDeclaredField("mHandler");
            f.setAccessible(true);
            try {
                f.set(subtitleInstance, new Handler());
            } catch (IllegalAccessException e) {
                return mediaplayer;
            } finally {
                f.setAccessible(false);
            }
            Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor",
                    cSubtitleController, iSubtitleControllerAnchor);
            setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
        } catch (Exception e) {
            Log.d(TAG,"getMediaPlayer crash ,exception = "+e);
        }
        return mediaplayer;
    }

    private MediaPlayer.OnErrorListener onErrorListener;

    public void setOnErrorListener(MediaPlayer.OnErrorListener onErrorListener) {
        this.onErrorListener = onErrorListener;
    }
}
